//
//  LSWrongQuesController.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/8/23.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSWrongQuesController.h"
#import "LSWrongQuesManager.h"
#import "LSFtpManager.h"
#import "LSModelQues.h"
#import "LSListenQuesView.h"
#import "LSReadQuesView.h"
#import "LSResultView.h"
#import "LSFollowReadView.h"
#import "KZAlertView.h"
#import "LSWrongCheckViewController.h"
#import "LSSpeedSetView.h"
#import "KZShadowButton.h"
#import "LSWrongQuesListManager.h"

#import "LSListenNewQuesView.h"
#import "LSReadNewQuesView.h"
#import "LSFollowNewQuesView.h"
#import "KZIndexProgressView.h"

@interface LSWrongQuesController ()<LSListenNewQuesViewDelegate,LSReadNewQuesViewDelegate,LSFollowReadNewQuesViewDelegate,UIPageViewControllerDelegate,UIPageViewControllerDataSource>

@property (nonatomic,assign) NSInteger currentIndex;
@property (nonatomic,assign) NSString *currentFileName;
@property (nonatomic,strong) LSModelQues *quesModel;
//@property (nonatomic,strong) UIButton *backBtn;
/*用来保存全部试题作答记录*/
@property (nonatomic,strong) NSMutableDictionary *allAnswerDict;
/*保存全部试题正确率记录*/
@property (nonatomic,strong) NSMutableDictionary *allRateDict;
/*全部试题model*/
@property (nonatomic,strong) NSMutableArray *allQuesModels;
/*时间*/
@property (nonatomic,strong) KZTimerView *timeView;
@property (nonatomic,strong) NSDate *allstartDate;
@property (nonatomic,strong) NSDate *dateStart;
@property (nonatomic,strong) NSDate *dateEnd;
@property (nonatomic,strong) UIButton *speedBtn;
@property (nonatomic,strong) LSSpeedSetView *speedSetView;
/*不同题型速度*/
@property (nonatomic,assign) NSInteger rateLayer1;//听力选择速度
@property (nonatomic,assign) NSInteger rateLayer2;//跟读速度
@property (nonatomic,assign) NSInteger rateLayer3;//朗读速度
@property (nonatomic,assign) BOOL isShowSpeedSet;
/*最后一题作答count*/
@property (nonatomic,assign) NSInteger lastQuesCount;
@property (nonatomic,strong) UIView *wrongComplteView;



/**
 进度表示
 */
@property (nonatomic,strong) KZIndexProgressView *progressView;

@property (nonatomic,assign) NSInteger index;

@property (nonatomic,strong) UIPageViewController *pageViewController;

@property (nonatomic,strong) NSMutableArray *vcArray;

@property (nonatomic,strong) LSWrongContentVC *pendingViewController;

/*白色遮罩*/
@property (nonatomic,strong) UIView *backwhiteView;

//调试按钮点击次数
@property (nonatomic,assign) NSInteger tapCount;

@end

@implementation LSWrongQuesController

- (UIView *)backwhiteView {
    if (!_backwhiteView) {
        _backwhiteView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kWidth, kHeight-kBottomPadding)];
        _backwhiteView.backgroundColor = [UIColor whiteColor];
    }
    return _backwhiteView;
}

- (void)setModel:(LSModelWrongQuesList *)model {
    _model = model;
    _allAnswerDict = [[NSMutableDictionary alloc] init];
    _allRateDict = [[NSMutableDictionary alloc] init];
    _allQuesModels = [NSMutableArray array];
    _isShowSpeedSet = YES;
    _rateLayer1 = 2;
    _rateLayer2 = 2;
    _rateLayer3 = 2;
    
    _tapCount = 2;
    //模拟数据
//    NSMutableArray *array = [NSMutableArray array];
//    for (NSInteger i = 0; i<1; i++) {
//        [array addObject:model.ItemInfoList[i]];
//    }
////    LSItemInfo *item = [[LSItemInfo alloc] init];
////    item.FtpUrl = @"url/IQOQWEUYJKDBZCHDH.atxz";
////    item.TypeID = @"Sq";
////    item.QuesID = @"IQOQWEUYJKDBZCHDH";
////    item.ResourceFrom = @"742";
////    [array addObject:item];
//    model.ItemInfoList = array;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initContentViewController];
    //在页面上，显示UIPageViewController对象的View
    [self addChildViewController:self.pageViewController];
    [self.view addSubview:self.pageViewController.view];
    UIScrollView *pageVCSrollView = [self findScrollView];
    pageVCSrollView.scrollEnabled = NO;
    
    if (!self.progressView ) {
        KZIndexProgressView *progressView = [[KZIndexProgressView alloc] init];
        progressView.totalIndex = _model.ItemInfoList.count;
        progressView.index = _currentIndex+1;
        self.progressView = progressView;
        [self.view addSubview:progressView];
        [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            if (@available(iOS 11.0, *)) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.height.mas_equalTo(48);
                
            } else {
                make.top.equalTo(self.view).offset(0);
                make.height.mas_equalTo(48);
            }
        }];
    }
    
    _currentIndex = 0;
    self.title = @"错题重做";
    [self addBYItemviews:@[@"LS-nav_back"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeLeft];

    UIImageView *navImageView = [[UIImageView alloc] init];
    navImageView.image = [UIImage imageNamed:@"LS-content_nav"];
    [self.view addSubview:navImageView];
    [navImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(kNavgationBar);
    }];
    
    NSString *string = KGetUserDefaults(@"ShowSpeedSet");
    if ([string isEqualToString:@"1"]) {
        _isShowSpeedSet = NO;
    } else {
        _isShowSpeedSet = YES;
    }
    _timeView = [[KZTimerView alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
   // if (!_isShowSpeedSet) {
    [_timeView start];
   // }
    
    WeakObj(self);
    _timeView.clickBlock = ^(BOOL isPause){
        
         if (isPause) {
             [[NSNotificationCenter defaultCenter] postNotificationName:@"TimePause" object:nil];
             
             //判断提示文字
             NSMutableAttributedString *muattr;
             
             LSWrongContentVC *vc = selfWeak.vcArray[selfWeak.currentIndex];
             LSBaseQuesView *quesView = vc.view.subviews.firstObject;
             LSItemInfo *item = selfWeak.model.ItemInfoList[selfWeak.currentIndex];
             if (quesView.pasueState != LSQuesPauseType_Recording || [item.TypeID isEqualToString:@"SE"] || [item.TypeID isEqualToString:@"E"]) {
                 NSString *text = @"劳逸结合能提高训练效率\n持之以恒能提升训练效果\n\n\t我等你回来哟~";
                 NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
                                                    initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
                 muattr = attr;
             } else if (quesView.pasueState== LSQuesPauseType_Recording) {
//                 NSString *text = @"劳逸结合能提高训练效率\n持之以恒能提升训练效果\n\n\t我等你回来哟~\n\n注意:若点击继续训练，本题将重新开始录音";
//                 NSRange range = [text rangeOfString:@"注意:若点击继续训练，本题将重新开始录音"];
//                 NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
//                                                    initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
//                 [attr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
                 NSString *text = @"哎呀，正在录音被你打断了，一会儿得重新开始了呦";
                 NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
                                                    initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
                 muattr = attr;
             }
             [selfWeak reset:muattr];
         }
    };
    [self addCustomItemviews:@[self.speedBtn,_timeView] position:ByNavigationItemPositionModeRight];
    
    [self loadAllFtpResData];
    
    self.allstartDate =[NSDate date];
    self.dateStart = [NSDate date];
  
}

//休息一下
- (void)reset:(NSMutableAttributedString*)muattr {
    
  //  LSItemInfo *item = self.model.ItemInfoList[self.currentIndex];
    KZAlertView *alert = [KZAlertView new];
    WeakObj(self);
    [alert showWithTitle:@"温馨提示" subtitle:muattr submitTypes:@[@0] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        
        [buttons.firstObject setTitle:@"继续训练" forState:UIControlStateNormal];
        
    } click:^(NSInteger index) {
        // 点击继续
        if (index == 0) {
            
            [selfWeak.timeView resume];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeResume" object:nil];
        }
        
    } destroyAtClickIndex:@[@0]];
}


- (void)back {
    if (_currentIndex==self.model.ItemInfoList.count) {
        
        [self.timeView stop];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
        UIView *quesView = [self.view viewWithTag:10000+_currentIndex];
        [[NSNotificationCenter defaultCenter] removeObserver:quesView];
        quesView = nil;
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
    } else {
        //先暂停
       // [self.timer setFireDate:[NSDate distantFuture]];
        [self.timeView pause];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TimePause" object:nil];
        
        //判断提示文字
        NSMutableAttributedString *muattr;
        LSWrongContentVC *vc= self.vcArray[_currentIndex];
        LSBaseQuesView *quesView = vc.view.subviews.firstObject;
        LSItemInfo *item = self.model.ItemInfoList[self.currentIndex];
        if (quesView.pasueState != LSQuesPauseType_Recording || [item.TypeID isEqualToString:@"SE"] || [item.TypeID isEqualToString:@"E"]) {
            
            NSString *text = @"你确定要退出\n  错题重做吗？";
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
                                               initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
            muattr = attr;
        } else if (quesView.pasueState == LSQuesPauseType_Recording) {
//            NSString *text = @"你确定要退出\n  错题重做吗？\n\n注意:若点击继续训练，本题将重新开始录音";
//            NSRange range = [text rangeOfString:@"注意:若点击继续训练，本题将重新开始录音"];
//            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
//                                               initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
//            [attr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
                                               initWithString:@"哎呀，正在录音被你打断了，一会儿得重新开始了呦" attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
            muattr = attr;
        }
        // 弹框提示
        KZAlertView *alert = [KZAlertView new];
        WeakObj(self);
        [alert showWithTitle:@"温馨提示" subtitle:muattr submitTypes:@[@0, @1] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
            
            [buttons.firstObject setTitle:@"退出训练" forState:UIControlStateNormal];
            [buttons.lastObject setTitle:@"继续训练" forState:UIControlStateNormal];
        } click:^(NSInteger index) {
            // 点击退出
            if (index == 0) {

                [selfWeak.timeView stop];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
                
                [selfWeak deleteAllUnZip];
                
                [selfWeak.navigationController dismissViewControllerAnimated:YES completion:nil];
                
            }
            // 点击继续
            else {
                //先恢复
                [selfWeak.timeView resume];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeResume" object:nil];
            }
            
        } destroyAtClickIndex:@[@0, @1]];
    }
    
}

- (void)deleteAllUnZip {
    for (NSInteger i = 0; i<_currentIndex+1; i++) {
        NSString *fileName = _model.ItemInfoList[i].QuesID;
        LSFtpManager *manager = [[LSFtpManager alloc] init];
        [manager deleteUnzip:fileName];
    }
    NSString *unzipPath = [NSString stringWithFormat:@"%@%@", NSHomeDirectory(),@"/Documents/record"];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:unzipPath];
    for (NSString *name in enumerator) {
        [[NSFileManager defaultManager] removeItemAtPath:[unzipPath stringByAppendingPathComponent:name] error:nil];
    }
}

#pragma mark - 网络请求&ftp下载
- (void)loadAllFtpResData { //目前先单道试题单独下载，后面思考修改成每20道下载一次
    
    LSItemInfo *item = _model.ItemInfoList[_currentIndex];
    if ([item.ResourceFrom isEqualToString:@"A00"]) { //数字化资源库
        
        LSWrongQuesManager *manager = [[LSWrongQuesManager alloc] init];
        NSDictionary *dict = @{@"QuesID":item.QuesID,@"StageNo":KGetUserDefaults(@"TestLayer")};
        manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
        
        WeakObj(self);
        [manager requestSZTKWithCompltionSuccess:^(LSModelQues *model) {
            NSLog(@"A00");
            selfWeak.quesModel = model;
            [selfWeak.allQuesModels addObject:model];
            dispatch_async(dispatch_get_main_queue(), ^{
                //[selfWeak createUI];
                LSWrongContentVC *vc= selfWeak.vcArray[_currentIndex];
                [selfWeak setUpUIwithFatherView:vc.view Index:_currentIndex];
                [selfWeak jumpToControllerIndex:_currentIndex];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
            
        } failuer:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"error:%@",error);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        }];
        
    } else if ([item.ResourceFrom isEqualToString:@"742"]) { //听说资源库
        //ftp下载数据
        NSString *ftpUrl = item.FtpUrl;
        NSArray *array = [ftpUrl componentsSeparatedByString:@"/"];
        self.currentFileName = [array.lastObject componentsSeparatedByString:@"."].firstObject;
        WeakObj(self);
        LSFtpManager *manager = [[LSFtpManager alloc] init];
        [manager LS_ftpdownloadFileName:self.currentFileName Path:ftpUrl Success:^(NSDictionary *pathDict, NSArray *names) {
            //            NSLog(@"全部：%@",names);
            //            NSLog(@"获取到数据：%@",pathDict);
            NSDictionary *xmlDic = [NSDictionary dictionaryWithXMLFile:pathDict[@"XML"]];
            LSQuestionType type;
            if ([item.TypeID isEqualToString:@"SE"]) {
                type = LSListeningTest;
            } else if ([item.TypeID isEqualToString:@"Sp"] || [item.TypeID isEqualToString:@"Spn"]) {
                type = LSReadingTest;
            } else {
                type = LSFollowSpeakingTest;
            }
            
            NSString *addressPath = [pathDict[@"XML"] stringByReplacingOccurrencesOfString:[pathDict[@"XML"] componentsSeparatedByString:@"/"].lastObject withString:@""];
            selfWeak.quesModel = [[LSModelQues alloc] initWithDict:xmlDic Type:type AddressPath:addressPath];
            [selfWeak.allQuesModels addObject: selfWeak.quesModel];
            // NSLog(@"%@",[selfWeak.quesModel yy_modelToJSONString]);
            
            NSLog(@"时间1：%f",[[NSDate date] timeIntervalSince1970] - [_dateStart timeIntervalSince1970]);
            dispatch_async(dispatch_get_main_queue(), ^{
                //[selfWeak createUI];
                LSWrongContentVC *vc= selfWeak.vcArray[_currentIndex];
                [selfWeak setUpUIwithFatherView:vc.view Index:_currentIndex];
                [selfWeak jumpToControllerIndex:_currentIndex];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                NSLog(@"时间2：%f",[[NSDate date] timeIntervalSince1970] - [_dateStart timeIntervalSince1970]);
            });
            
        } failuer:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"error:%@",error);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        }];
    }
    
}


- (UIButton *)speedBtn
{
    if (!_speedBtn) {
        _speedBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40,40)];
        [_speedBtn setImage:[UIImage imageNamed:@"LS-1.0x"] forState:UIControlStateNormal];
        [_speedBtn addTarget:self action:@selector(showSpeedSetView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _speedBtn;
}

//调速功能
- (void)showSpeedSetView {
    
    LSWrongContentVC *vc = self.vcArray[_currentIndex];
    UIView *view = vc.view.subviews.firstObject;
    
    _tapCount = _tapCount+1;
    if (_tapCount>3) {
        _tapCount=1;
    }
    if (_tapCount==3) {
        
         [self.speedBtn setImage:[UIImage imageNamed:@"LS-1.2x"] forState:UIControlStateNormal];
        _rateLayer1 = 3;
        _rateLayer2 = 3;
        _rateLayer3 = 3;
        
        [self resetView:view RateLayer:3];
        
    } else if (_tapCount==2) {
        
        [self.speedBtn setImage:[UIImage imageNamed:@"LS-1.0x"] forState:UIControlStateNormal];
        _rateLayer1 = 2;
        _rateLayer2 = 2;
        _rateLayer3 = 2;
        
        [self resetView:view RateLayer:2];

    } else if (_tapCount==1) {
        
        [self.speedBtn setImage:[UIImage imageNamed:@"LS-0.8x"] forState:UIControlStateNormal];
        _rateLayer1 = 1;
        _rateLayer2 = 1;
        _rateLayer3 = 1;
        
        [self resetView:view RateLayer:1];
    }
}

- (void)resetView:(UIView*)view RateLayer:(NSInteger)rateLayer {
    NSString *value = KGetUserDefaults(@"FirstSpeedBtn");//第一次点击调速按钮
    if ([value isEqualToString:@"2"]) {
        if ([view isKindOfClass:[LSListenNewQuesView class]]) {
            LSListenNewQuesView *newView = (LSListenNewQuesView*)view;
            [newView reStartSource:rateLayer];
            
        } else if ([view isKindOfClass:[LSReadNewQuesView class]]) {
            LSReadNewQuesView *newView = (LSReadNewQuesView*)view;
            [newView reStartSource:rateLayer];
            
        } else if ([view isKindOfClass: [LSFollowNewQuesView class]]) {
            LSFollowNewQuesView *newView = (LSFollowNewQuesView*)view;
            [newView reStartSource:rateLayer];
            
        }
    } else {
        KUserDefaults(@"2", @"FirstSpeedBtn");
        //弹窗
        KZAlertView *alert = [KZAlertView new];
        NSMutableAttributedString *muattr = [[NSMutableAttributedString alloc] initWithString:@"调速按钮可以调整试题作答速度,\n调整速度后本题将重新开始作答\n\n(此弹窗只显示一次)"];
        WeakObj(self);
        [selfWeak.timeView pause];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TimePause" object:nil];
        [alert showWithTitle:@"温馨提示" subtitle:muattr submitTypes:@[@0] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
            
            [buttons.firstObject setTitle:@"继续训练" forState:UIControlStateNormal];
            
        } click:^(NSInteger index) {
            // 点击继续
            if (index == 0) {
                
                [selfWeak.timeView resume];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeResume" object:nil];
                
                if ([view isKindOfClass:[LSListenNewQuesView class]]) {
                    LSListenNewQuesView *newView = (LSListenNewQuesView*)view;
                    [newView reStartSource:rateLayer];
                    
                } else if ([view isKindOfClass:[LSReadNewQuesView class]]) {
                    LSReadNewQuesView *newView = (LSReadNewQuesView*)view;
                    [newView reStartSource:rateLayer];
                    
                } else if ([view isKindOfClass: [LSFollowNewQuesView class]]) {
                    LSFollowNewQuesView *newView = (LSFollowNewQuesView*)view;
                    [newView reStartSource:rateLayer];
                    
                }
                
            }
            
        } destroyAtClickIndex:@[@0]];
    }
   
}

#pragma mark - 创建视图
- (void)setUpUIwithFatherView:(UIView*)fatherView Index:(NSInteger)index{
    
    LSItemInfo *item = _model.ItemInfoList[_currentIndex];
    
    if([item.TypeID isEqualToString:@"SE"] || [item.TypeID isEqualToString:@"E"]) {//听力
        
        LSListenNewQuesView *quesView = [[LSListenNewQuesView alloc] initWithFrame:CGRectMake(0,kNavgationBar+48,kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.delegate = self;
        quesView.speedLayer = self.rateLayer1;
        self.quesModel = self.allQuesModels[index];
        if ([item.TypeID isEqualToString:@"SE"]) {
            self.quesModel.ReadTime =  item.ReadTime;
            self.quesModel.WaitTime = item.WaitTime;
            self.quesModel.RecordTime = item.RecordTime;
        }
        quesView.model = self.quesModel;
        [fatherView addSubview:quesView];
        
    } else if ([item.TypeID  isEqualToString:@"Spn"]) { //朗读
        
        LSReadNewQuesView *quesView = [[LSReadNewQuesView alloc] initWithFrame:CGRectMake(0,kNavgationBar+48,kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.delegate = self;
        quesView.speedLayer = self.rateLayer3;
        self.quesModel = self.allQuesModels[index];
        self.quesModel.ReadTime =  item.ReadTime;
        self.quesModel.WaitTime = item.WaitTime;
        self.quesModel.RecordTime = item.RecordTime;
        quesView.model = self.quesModel;
        [fatherView addSubview:quesView];
        
    } else { //跟读
        
        LSFollowNewQuesView *quesView = [[LSFollowNewQuesView alloc] initWithFrame:CGRectMake(0, kNavgationBar+48, kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.delegate  = self;
        quesView.speedLayer = self.rateLayer2;
        self.quesModel = self.allQuesModels[index];
        self.quesModel.ReadTime =  item.ReadTime;
        self.quesModel.WaitTime = item.WaitTime;
        self.quesModel.RecordTime = item.RecordTime;
        quesView.model = self.quesModel;
        [fatherView addSubview:quesView];
    }
}


#pragma mark - LSListenQuesViewDelegate
- (void)retrunShowComplteView {
    
//    LSQuesView *quesView = [self.view viewWithTag:10000+_currentIndex];
//    [quesView stopClickNextBtn];

    if(_currentIndex==self.model.ItemInfoList.count-1)
    {
        [self showComplteView];
    }
}

- (void)willEnterNextQues {
    NSLog(@"/////进入下一题");

    self.dateStart = [NSDate date];
//    UIView *quesView = [self.view viewWithTag:10000+_currentIndex];
//    [quesView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.view.mas_left);
//        make.left.equalTo(self.view.mas_left).offset(-kWidth);
//    }];
    [UIView animateWithDuration:0.3 animations:^{
        
        [self.view layoutIfNeeded];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
        
    } completion:^(BOOL finished) {
        _currentIndex = _currentIndex + 1;
        if(_currentIndex<_model.ItemInfoList.count) {
            
            [self loadAllFtpResData];
            
        } else {
            [self showComplteView];
        }
    }];
}

#pragma mark - LSListenQuesViewDelegate
- (void)FinishAnswerQues:(NSDictionary *)answerDict CorrectRate:(CGFloat)correctRate IsSave:(BOOL)isSave {
    
    //保存当前currentIndex作答记录
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
    [self.allAnswerDict setObject:dict forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
  
    if (correctRate>=1.00) {
        [self.allRateDict setObject:@(correctRate) forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    } else {
        [self.allRateDict setObject:@(correctRate) forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    }
    
    NSLog(@"//////进行保存");
    //NSLog(@"/////%@",answerDict);
    NSMutableArray *stuAnsArr = [NSMutableArray array];
    self.quesModel = self.allQuesModels[_currentIndex];
    for (NSInteger i = 0;i<self.quesModel.TotalItemCount;i++) {
        NSString *stuAnswer = [answerDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
        if(stuAnswer == nil) {
           stuAnswer = @"";
        }
        LSChild *child = self.quesModel.ChildList[i];
        NSDictionary *stuAns = @{@"ChildIndex":@(i+1),
                                 @"StuAnswer":stuAnswer,
                                 @"Answer":child.ChildAnswer
                                 };
        [stuAnsArr addObject:stuAns];
    }
    
    self.dateEnd = [NSDate date];
    NSInteger dur = [self.dateEnd timeIntervalSince1970]-[self.dateStart timeIntervalSince1970];
    LSItemInfo *item = _model.ItemInfoList[_currentIndex];
    NSDictionary *saveParam = @{@"StageNo":KGetUserDefaults(@"TestLayer"),
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"StuID":DR_UserInfo.UserID,
                           @"QuesID":item.QuesID,
                           @"TypeID":item.TypeID,
                           @"TotalItemCount":@(self.quesModel.TotalItemCount),
                           @"AnswerItemCount":@(answerDict.count),
                           @"CorrectRate":@(correctRate),
                                 @"Score":@{},
                           @"StuAnswer":stuAnsArr,
                           @"ResourceFrom":item.ResourceFrom,
                           @"Duration":@(dur),
                           @"CreateTime":item.CreateTime,
                                @"Stage":@(self.rateLayer1),
                                @"ImportKlgCode":item.ImportKlgCode?item.ImportKlgCode:@""
                           };
    NSLog(@"%@",[NSObject objectToJson:saveParam]);
    //调用错题保存接口
    LSWrongQuesManager *manager = [[LSWrongQuesManager alloc] init];
    manager.requestParam = saveParam;
    [manager requestSaveWrongQuesWithCompltionSuccess:^(NSString *string) {
        
    } failuer:^(NSString *error) {
        
    }];
    
}


#pragma mark - ReadDelegate
- (void)FinishAnswerWordDict:(NSDictionary*)answerDict IsSave:(BOOL)isSave{
    //保存当前currentIndex作答记录
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
    [self.allAnswerDict setObject:dict forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    NSString *score = dict[@"result"][@"overall"];
    [self.allRateDict setObject:@(score.floatValue/100.00) forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    
    NSLog(@"//////进行保存");
    
    NSLog(@"%@",[NSObject objectToJson:dict]);
    NSDictionary *resultDict = dict[@"result"];
    //句子
    NSMutableArray *senmuarr = [NSMutableArray array];
    NSArray *sentences = resultDict[@"sentences"];
    for (NSInteger i = 0; i<sentences.count; i++) {
        
        NSDictionary *dictionary = sentences[i];
        NSArray *details = dictionary[@"details"];
        NSMutableArray *wordmuarr = [NSMutableArray array];
        //单词
        for (NSInteger j = 0; j<details.count; j++) {
            NSDictionary *wordDic = details[j];
            NSDictionary *wordScoreDict = @{@"TotalScore":wordDic[@"overall"],
                                            @"Word":wordDic[@"word"]
                                            };
            [wordmuarr addObject:wordScoreDict];
        }
        
        NSDictionary *senScoreDict = @{@"TotalScore":dictionary[@"overall"],
                                       @"Sentence":dictionary[@"sentence"],
                                       @"WordList":wordmuarr
                                       };
        [senmuarr addObject:senScoreDict];
    }
    

    NSDictionary *scoreDict = @{@"TotalScore":resultDict[@"overall"],
                                @"Integrity":NotNull(resultDict[@"integrity"]),
                                @"Fluency":NotNull(resultDict[@"fluency"]),
                                @"Rhythm":NotNull(resultDict[@"rhythm"]),
                                @"Pronunciation":NotNull(resultDict[@"pronunciation"]),
                                @"SentenceList":senmuarr
                                };
    
    LSItemInfo *item = _model.ItemInfoList[_currentIndex];
    
    self.dateEnd = [NSDate date];
    NSInteger dur = [self.dateEnd timeIntervalSince1970]-[self.dateStart timeIntervalSince1970];

    NSDictionary *saveParam = @{@"StageNo":KGetUserDefaults(@"TestLayer"),
                                @"SchoolID":KGetUserDefaults(@"SchoolID"),
                                @"StuID":DR_UserInfo.UserID,
                                @"QuesID":item.QuesID,
                                @"TypeID":item.TypeID,
                                @"TotalItemCount":@(1),
                                @"AnswerItemCount":@(1),
                                @"CorrectRate":@(score.floatValue/100.00),
                                @"Score":scoreDict,
                                @"StuAnswer":@[],
                                @"ResourceFrom":item.ResourceFrom,
                                @"Duration":@(dur),
                                @"CreateTime":item.CreateTime,
                                @"Stage":@(self.rateLayer3),
                                @"ImportKlgCode":item.ImportKlgCode?item.ImportKlgCode:@""
                                
                                };
    //调用错题保存接口
    LSWrongQuesManager *manager = [[LSWrongQuesManager alloc] init];
    manager.requestParam = saveParam;
    [manager requestSaveWrongQuesWithCompltionSuccess:^(NSString *string) {
        
    } failuer:^(NSString *error) {
        
    }];
}

#pragma mark - FollowReadDelegate
- (void)FinishAnswerSenDict:(NSDictionary*)answerDict RefText:(NSString *)refText IsSave:(BOOL)isSave {
    //保存当前currentIndex作答记录
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
    [self.allAnswerDict setObject:dict forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    NSString *score = dict[@"result"][@"overall"];
    [self.allRateDict setObject:@(score.floatValue/100.00) forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    
    NSLog(@"//////进行保存");
    NSLog(@"%@",[NSObject objectToJson:dict]);
    NSDictionary *resultDict = dict[@"result"];
    
    NSMutableArray *muarr = [NSMutableArray array];
    NSArray *words = resultDict[@"words"];
    for (NSInteger i = 0; i<words.count; i++) {
        NSDictionary *dictionary = words[i];
        
        NSDictionary *wordDict = @{@"TotalScore":dictionary[@"scores"][@"overall"],
                                   @"Word":dictionary[@"word"]
                                   };
        [muarr addObject:wordDict];
    }
    
    NSDictionary *senScoreDict = @{@"TotalScore":resultDict[@"overall"],
                                   @"Sentence":refText,
                                   @"WordList":muarr
                                   };
    
    NSDictionary *scoreDict = @{@"TotalScore":resultDict[@"overall"],
                                @"Integrity":resultDict[@"overall"],
                                @"Fluency":resultDict[@"overall"],
                                @"Rhythm":resultDict[@"overall"],
                                @"Pronunciation":resultDict[@"overall"],
                                @"SentenceList":@[senScoreDict]
                                };
    
    LSItemInfo *item = _model.ItemInfoList[_currentIndex];
    
    self.dateEnd = [NSDate date];
    NSInteger dur = [self.dateEnd timeIntervalSince1970]-[self.dateStart timeIntervalSince1970];
    NSDictionary *saveParam = @{@"StageNo":KGetUserDefaults(@"TestLayer"),
                                @"SchoolID":KGetUserDefaults(@"SchoolID"),
                                @"StuID":DR_UserInfo.UserID,
                                @"QuesID":item.QuesID,
                                @"TypeID":item.TypeID,
                                @"TotalItemCount":@(1),
                                @"AnswerItemCount":@(1),
                                @"CorrectRate":@(score.floatValue/100.00),
                                @"Score":scoreDict,
                                @"StuAnswer":@[],
                                @"ResourceFrom":item.ResourceFrom,
                                @"Duration":@(dur),
                                @"CreateTime":item.CreateTime,
                                @"Stage":@(self.rateLayer2),
                                @"ImportKlgCode":item.ImportKlgCode?item.ImportKlgCode:@""
                                };
    NSLog(@"得分：%@",score);
    NSLog(@"%@",[NSObject objectToJson:saveParam]);
    //调用错题保存接口
    LSWrongQuesManager *manager = [[LSWrongQuesManager alloc] init];
    manager.requestParam = saveParam;
    [manager requestSaveWrongQuesWithCompltionSuccess:^(NSString *string) {
        
    } failuer:^(NSString *error) {
        
    }];
}

- (void)showComplteView {
    
    NSInteger count = 0;
    for(NSInteger i = 0 ; i<_model.ItemInfoList.count;i++) {
        
        LSItemInfo *item = _model.ItemInfoList[i];
        if ([item.TypeID isEqualToString:@"SE"] || [item.TypeID isEqualToString:@"E"]) {
            //正确率等于1为正确
            CGFloat correct = LS_System.listenScore/100.0;
            NSNumber *num = [self.allRateDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
            if (num.floatValue>=correct) {
                count++;
            }
            
        } else {
            //正确率大于等于0.8为正确
            CGFloat correct = LS_System.readScore/100.0;
            NSNumber *num = [self.allRateDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
            if (num.floatValue>=correct) {
                count++;
            }
        }
    }
    
    if (count==_model.ItemInfoList.count) {
        //判断错题全部作答正确显示
        self.wrongComplteView  = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
        self.wrongComplteView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:_wrongComplteView];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(49,112,kWidth-49*2,275)];
        imageView.image = [UIImage imageNamed:@"LS-弹出"];
        [_wrongComplteView addSubview:imageView];
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth-160)/2,imageView.y+imageView.height, 160, 35)];
        [_wrongComplteView addSubview:btn];
        [btn setTitle:@"好的" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"LS-好的按钮背景"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(hideComplteView) forControlEvents:UIControlEventTouchUpInside];
        
    } else {
        
        //判断错题非全部作答正确显示
        dispatch_async(dispatch_get_main_queue(), ^{
            NSAttributedString *attr = [[NSAttributedString alloc] initWithString:@"本轮错题训练仍有未通过的试题,\n是否重新训练\n(试题作答以第一次结果为准)"];
            KZAlertView *alertView = [KZAlertView new];
            WeakObj(self);
            [alertView showWithTitle:@"温馨提示" subtitle:attr submitTypes:@[@0,@1] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
                
                [buttons.firstObject setTitle:@"退出训练" forState:UIControlStateNormal];
                [buttons.lastObject setTitle:@"重新训练" forState:UIControlStateNormal];
                
            } click:^(NSInteger index) {
                
                if(index==0) { //退出训练
                    [selfWeak.timeView stop];
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
                    UIView *quesView = [self.view viewWithTag:10000+_currentIndex];
                    [[NSNotificationCenter defaultCenter] removeObserver:quesView];
                    quesView = nil;
                    
                    [selfWeak deleteAllUnZip];
                    
                    [selfWeak.navigationController dismissViewControllerAnimated:YES completion:nil];
                    
                } else { //重新训练
                    
                    [selfWeak reloadData];
                    
                }
                
            } destroyAtClickIndex:@[@0,@1]];
        });
        
    }
   
}

- (void)reloadData {
    [self.timeView start];
    
    UIView *quesView = [self.view viewWithTag:10000+_currentIndex];
    [quesView removeFromSuperview];
    quesView = nil;

    LSWrongQuesListManager *manager = [[LSWrongQuesListManager alloc] init];
    NSDictionary *dict = @{@"StuID":DR_UserInfo.UserID,
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"StageNo":KGetUserDefaults(@"TestLayer"),
                           @"TypeID":@"-1"
                           };
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    WeakObj(self);
    [manager requestWithCompltionSuccess:^(LSModelWrongQuesList *model) {
        selfWeak.model = model;
        selfWeak.currentIndex = 0;
       // [selfWeak loadData];
        [selfWeak loadAllFtpResData];
        
    } failuer:^(NSString *error) {
        
    }];


}

- (void)hideComplteView {
    
    [self.wrongComplteView removeFromSuperview];
    self.wrongComplteView = nil;
    
    [self.timeView stop];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
    UIView *quesView = [self.view viewWithTag:10000+_currentIndex];
    [[NSNotificationCenter defaultCenter] removeObserver:quesView];
    quesView = nil;
    [self deleteAllUnZip];
    
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - 其他
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
    
//    if (_isShowSpeedSet) {
//        [self showSpeedSetView];
//        KUserDefaults(@"1", @"ShowSpeedSet");
//    } else {
//        [self loadData];
//    }
}

-(void)leftItemsAction:(NSInteger)leftIndex {
    
    [self back];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

   // [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    NSLog(@"销毁");
}

#pragma mark - pageViewController相关
- (UIScrollView *)findScrollView{
    UIScrollView *scrollView;
    for (id subview in self.pageViewController.view.subviews) {
        if ([subview isKindOfClass:[UIScrollView class]]) {
            scrollView = subview;
            break;
        }
    }
    return scrollView;
}

- (UIPageViewController *)pageViewController {
    if (!_pageViewController) {
        NSDictionary *options = @{UIPageViewControllerOptionInterPageSpacingKey : @(0)};
        // 根据给定的属性实例化UIPageViewController
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                              navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                            options:options];
        // 设置UIPageViewController代理和数据源
        _pageViewController.delegate = self;
        _pageViewController.dataSource = self;
        
        // [self jumpToControllerIndex:0];
        
        // 设置UIPageViewController 尺寸
        _pageViewController.view.frame = CGRectMake(0,0,kWidth, kHeight-kBottomPadding);
        
    }
    return _pageViewController;
}

- (void)initContentViewController {
    self.vcArray = [[NSMutableArray alloc] init];
    
    NSDate *date = [NSDate date];
    for (int i = 0; i<self.model.ItemInfoList.count; i++) {
        @autoreleasepool {
            LSWrongContentVC *vc = [[LSWrongContentVC alloc] init];
            vc.wrongItem = self.model.ItemInfoList[i];
            [self.vcArray addObject:vc];
        }
    }
    
    NSLog(@"耗时：%f",[[NSDate date] timeIntervalSince1970] - [date timeIntervalSince1970]);
}

- (void)jumpToControllerIndex:(NSInteger)index {
    [self.view endEditing:YES];
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.backwhiteView removeFromSuperview];
    
    LSWrongContentVC * initialViewController = self.vcArray[index];
    if (initialViewController.view.subviews.count==0) {
        [self setUpUIwithFatherView:initialViewController.view Index:index];
    }
    for (UIView *view in initialViewController.view.subviews ) {
        if ([view isKindOfClass:[LSListenNewQuesView class]]) {
            
            LSListenNewQuesView *newView = (LSListenNewQuesView*)view;
            [newView startSource];
            
        } else if ([view isKindOfClass:[LSReadNewQuesView class]]) {
            
            LSReadNewQuesView *newView = (LSReadNewQuesView*)view;
            [newView startSource];
        } else {
            
            LSFollowNewQuesView *newView = (LSFollowNewQuesView*)view;
            [newView startSource];
            
        }
    }
    
    self.progressView.index = index+1;
    NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
    
    [_pageViewController setViewControllers:viewControllers
                                  direction:UIPageViewControllerNavigationDirectionForward
                                   animated:YES
                                 completion:nil];
}

#pragma mark - pageViewControll Delegate DataSource
#pragma mark - 数组元素值，得到下标值
- (NSUInteger)indexOfViewController:(LSWrongContentVC *)viewController {
    
    return [self.model.ItemInfoList indexOfObject:viewController.wrongItem];
}


#pragma mark ----- UIPageViewControllerDelegate -----
//开始滚动或翻页的时候触发
- (void)pageViewController:(UIPageViewController *)pageViewController
willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    
    _pendingViewController = (LSWrongContentVC*)pendingViewControllers.lastObject;
    
    [self.view endEditing:YES];
}

//结束滚动或翻页的时候触发
- (void)pageViewController:(UIPageViewController *)pageViewController
        didFinishAnimating:(BOOL)finished
   previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers
       transitionCompleted:(BOOL)completed {
    
    NSInteger index = [self indexOfViewController:_pendingViewController];//滚动结束后的index
    NSLog(@"当前的index是：%ld",(long)index);
    self.progressView.index = index+1;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_pendingViewController.view.subviews.count==0) {
            [self setUpUIwithFatherView:_pendingViewController.view Index:index];
        }
    });
}

#pragma mark ----- UIPageViewControllerDataSource -----
#pragma mark 返回上一个ViewController对象
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    
    [self.view endEditing:YES];
    
    NSUInteger index = [self indexOfViewController:(LSWrongContentVC *)viewController];
    
    if ((index == 0) || (index == NSNotFound)) {
        return nil;
    }
    index--;
    // 返回的ViewController，将被添加到相应的UIPageViewController对象上。
    // UIPageViewController对象会根据UIPageViewControllerDataSource协议方法,自动来维护次序
    // 不用我们去操心每个ViewController的顺序问题
    return self.vcArray[index];
    
}

#pragma mark - 返回下一个ViewController对象

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    
    [self.view endEditing:YES];
    
    NSUInteger index = [self indexOfViewController:(LSWrongContentVC*)viewController];
    
    if (index == NSNotFound) {
        return nil;
    }
    index++;
    
    if (index == [self.model.ItemInfoList count]) {
        return nil;
    }
    
    return self.vcArray[index];
}


@end

@implementation LSWrongContentVC

@end
